package com.study.mike.common.utils;

import cn.hutool.json.JSONUtil;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author KangHui
 * @Date 2022/7/4 16:40
 */
@Component
public class QiniuUtil {
    @Value("${qiniu.accesskey}")
    private String AccessKey;
    @Value("${qiniu.secretkey}")
    private String SecretKey;
    @Value("${qiniu.bucketname}")
    private String bucketName;

    public String upload(MultipartFile file, String fileName) {

        //构造Region对象的配置类(创建牛七云的configuration对象)
        Configuration cfg = new Configuration(Region.region2());
        UploadManager uploadManager = new UploadManager(cfg);

        try {
            byte[] uploadBytes = file.getBytes();
            Auth auth = Auth.create(AccessKey, SecretKey);
            String upToken = auth.uploadToken(bucketName);
            Response response = uploadManager.put(uploadBytes, fileName, upToken);
            //解析上传成功的结果
            DefaultPutRet putRet = JSONUtil.toBean(response.bodyString(), DefaultPutRet.class);
            return putRet.key;
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }
}
